import os from 'os';
import * as net from 'net';

export function getLocalIp() {
  const interfaces = os.networkInterfaces().WLAN;
  if (!interfaces) {
    return null;
  }
  const locals = interfaces.filter((i) => i.family === 'IPv4').filter((i) => /^(172|192)/.test(i.address));

  if (locals.length) {
    return locals[0].address;
  }
  return null;
}

/**
 * 判断主机端口是否被占用
 * @param host
 * @param port
 * @param callback
 */
export function isPortOccupied(
  host: string,
  port: number,
  callback: (error: Error | null, flag: boolean | null) => void
) {
  const server = net.createServer().listen({ host, port });
  server.on('listening', () => {
    server.close();
  });
  server.on('close', () => {
    callback && callback(null, false);
  });
  server.on('error', (error: any) => {
    if (error.code === 'EADDRINUSE') {
      callback && callback(null, true);
    } else {
      callback(error, null);
    }
  });
}
